<?php

namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Server\Contract\MiddlewareInterface;

/**
 * @Bean()
 */

class ControllerMiddleware implements MiddlewareInterface
{
    /**
     *  Process an incoming server request.
     *
     */
    public function process(ServerRequestInterface $request , RequestHandlerInterface $handler) :ResponseInterface
    {
         if ('OPTIONS' === $request->getMethod()) {
            $res = [
                'code' => 0,
                'msg' => '成功',
                'data' => []
            ];
            return \context()->getResponse()
                ->withHeader('Access-Control-Allow-Credentials',true)
                ->withHeader('Access-Control-Allow-Origin', '*')
                ->withHeader('Access-Control-Allow-Headers' , 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,x-Vendor-Authorization,X-Vendor-Host,x-XT-Authorization')
                ->withContentType(ContentType::JSON)
                ->withStatus(200)
                ->withContent(json_encode($res));
        }

        return $handler->handle($request);
    }
}